
package io.zhifei.modules.app.login.resolver;

import io.zhifei.modules.app.login.annotation.LoginUser;
import io.zhifei.modules.app.login.form.UserFrom;
import io.zhifei.modules.app.login.interceptor.AuthorizationInterceptor;
import io.zhifei.modules.app.login.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.Map;

/**
 * 有@LoginUser注解的方法参数，注入当前登录用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private LoginService userService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(UserFrom.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        //获取用户ID
        Object object = request.getAttribute(AuthorizationInterceptor.USER_KEY, RequestAttributes.SCOPE_REQUEST);
        if (object == null) {
            return null;
        }
        //获取是客户，还是学员
        Map<String, Object> user = userService.getMemberOrCustomer(Long.valueOf(object.toString()));
        UserFrom userFrom = new UserFrom();
        userFrom.setUserId(user.get("id").toString());
        userFrom.setUserName(user.get("name").toString());
        return userFrom;
    }
}
